<script setup>
import { ref,watch,onMounted } from 'vue'
import { searchAll,saveEmpExpr,getEmpById,updateEmpDate,deleteByIdEmp } from '@/api/emp'
import { queryDept } from '@/api/dept'
import { ElMessage } from 'element-plus'

const jobName = ref([{name:'班主任',value:1},{name:'讲师',value:2},{name:'学工主管',value:3},{name:'教研主管',value:4},{name:'人事部',value:5},{name:'其他',value:6}])
// 部门列表
const deptList = ref([])
//查询部门信息
const deptNameLiatDate =async()=>{
  const res = await queryDept()
  if(res.code){
    deptList.value = res.data
  }
}

const empExprList = ref({
  image:'',
  username:'',
  name:'',
  gender:'',
  job:'',
  entryDate:'',
  deptId:'',
  phone:'',
  salary:'',
  exprList:[]
})

//分页查询
const searchPage =async()=>{
  const res = await searchAll(currentPage.value,pageSize.value,formEmpSearch.value.name,
  formEmpSearch.value.gender,formEmpSearch.value.begin,formEmpSearch.value.end)
  if(res.code){
      empList.value = res.data.rows
      total.value = res.data.total
  }
}
//清空
const clear=()=>{
  formEmpSearch.value = {name: '', gender: '', date: [], begin: '', end: ''}
  searchPage()
}

//页面加载时始化分页数据
onMounted(()=>{
  searchPage()
  deptNameLiatDate()
  //加载token令牌
  getToken()
})

const formEmpSearch = ref({
  name: '',
  gender: '',
  date: [],
  begin: '',
  end: ''
})
const size = 'default'
const background = true
const disabled = false
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const table = ref(null)

const empList = ref([])


//定义表单引用的ref
const ruleFormRef = ref(null)

// 验证规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 10, message: '用户名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/g, message: '请输入有效的手机号', trigger: 'blur' }
  ]
});

// 监听日期，默认是浅层侦听，使用deep属性，才是深度侦听
watch(()=>formEmpSearch.value.date,(newValue,oldValue)=>{//newValue是更新后的值 oldValue是更新前的值
  if(newValue.length==2){
    formEmpSearch.value.begin = newValue[0]
    formEmpSearch.value.end = newValue[1]
  }else{
    formEmpSearch.value.begin = ''
    formEmpSearch.value.end = ''
  }
})
// 新增员工对话框的显示与隐藏
const dialogShow = ref(false)
// 新增员工的点击时间，弹出新增员工对话框
const addEmp = ()=>{ 
  dialogShow.value = true
  table.value = '新增员工'
  empExprList.value = {
    image:'',
    username:'',
    name:'',
    gender:'',
    job:'',
    entryDate:'',
    deptId:'',
    phone:'',
    salary:'',
    exprList:[]
  }
// 清空表单
  if(ruleFormRef.value){
    ruleFormRef.value.resetFields()
  }
}

//回显查询员工信息
const edit = async(id) =>{ 
  const res = await getEmpById(id)
  empExprList.value = res.data
  dialogShow.value = true
  table.value = '修改员工'
    // 清空表单
  if(ruleFormRef.value){
    ruleFormRef.value.resetFields()
  }
  // 回显表单给员工经历的时间来赋值
  empExprList.value.exprList.forEach(item => { 
    //要创建新数组来赋值
    item.exprDate = [item.begin,item.end]
  });
}

//定义批量删除员工的id集合
const ids = ref([])
//获取选中员工的id集合
const handleSelectionChange = (value) => {
  ids.value = value.map(item => item.id)
}
//批量删除员工信息
const deleteById = async () => {
  const result = await deleteByIdEmp(ids.value)
  searchPage();
}
//单个删除员工信息
const deleteId = async (id) => { 
  const result = await deleteByIdEmp(id)
  searchPage();
}

//保存员工信息的方法
const save=()=>{ 
  if (!ruleFormRef) return
  ruleFormRef.value.validate(async (valid, fields) => {
    let result = null
    if (valid) {//表单验证成功
      if(empExprList.value.id){
        result = await updateEmpDate(empExprList.value)
      }else{
        result = await saveEmpExpr(empExprList.value)
      }
    } else {
      console.log('error submit!', fields)
    }
    if(result.code){ 
      //关闭弹框
      dialogShow.value = false
      //刷新员工列表
      searchPage()
      //提示成功
      ElMessage.success('操作成功')
    }else{ 
      ElMessage.error('操作失败')
    }
})  
}

//侦听工作经历的date时间
watch(()=>empExprList.value.exprList, (newValue, oldValue) => {
  // 判断 exprList 是否存在且不为空数组
  if(empExprList.value.exprList && empExprList.value.exprList.length>0) {
    empExprList.value.exprList.forEach(item=>{ 
      item.begin = item.exprDate[0]
      item.end = item.exprDate[1]
})
  }
},{deep:true})
//改变每页显示的数据条数
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  //当改变每页显示的数据条数时，页码变为1
  currentPage.value = 1
  searchPage();
}
//改变页码大小
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  searchPage();
}

//添加工作经历的点击事件
const addExprWork = () => { 
  // 添加工作经历
  empExprList.value.exprList.push({company:'',job:'',begin:'',end:'',exprDate:[]})
}
//删除工作经历的点击事件
const deleteExpr = (index) => { 
  // 删除数组中的元素
  empExprList.value.exprList.splice(index,1)
}
//文件上传来获取token
const token = ref({token:''})
//写一个方法来获取token
const getToken = () =>{
  let loginInfo = JSON.parse(localStorage.getItem('loginUser'))
  if(loginInfo){ 
    token.value =loginInfo.token
  }
}

//文件上传
//文件上传成功后，将响应的结果回调
const handleAvatarSuccess= (response) => {
 empExprList.value.image = response.data
}
//文件上传之前的格式和大小校验
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('文件上传的格式为jpeg')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文件的大小不能超过 2MB!')
    return false
  }
  return true
}
</script>

<template>
  <h1>员工管理</h1>
  <!-- 搜索栏 -->
  <div>
    <el-button type="primary" style="margin: 20px;" @click="addEmp" >新增员工</el-button>
    <el-button type="primary" style="margin: 20px;" @click="deleteById" >批量删除</el-button>
  </div>
  <!-- 查询表单 -->
  <el-form :inline="true" :model="formEmpSearch" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="formEmpSearch.name" placeholder="请输入名字" style="width: 200px;" />
    </el-form-item>
    <el-form-item label="性别">
      <el-select v-model="formEmpSearch.gender" placeholder="请选择" style="width: 200px;">
        <el-option label="男" value="1" />
        <el-option label="女" value="2" />
      </el-select>
    </el-form-item>
    <el-form-item label="入职日期">
      <el-date-picker v-model="formEmpSearch.date" type="daterange" range-separator="到"
        start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" :size="default"/>
        <!-- value-format="YYYY-MM-DD"是要格式化时间 -->
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="searchPage">查询</el-button>
      <el-button type="info" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>

  <div>
    <!-- 表格 -->
    <el-table :data="empList" @selection-change="handleSelectionChange" border style="width: 100%">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="主键ID" width="80" align="center"/>
      <el-table-column prop="name" label="姓名" width="150" align="center"/>
      <el-table-column label="性别" width="100" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.gender==1">男</el-tag>
          <el-tag v-else>女</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="头像" width="180" align="center">
        <template #default="scope">
          <img :src="scope.row.image" style="width: 50px; height: 50px;"></img>
        </template>
      </el-table-column>
      <el-table-column label="部门" width="100" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.job==1">班主任</el-tag>
          <el-tag v-else-if="scope.row.job==2">讲师</el-tag>
          <el-tag v-else-if="scope.row.job==3">学工主管</el-tag>
          <el-tag v-else-if="scope.row.job==4">教研主管</el-tag>
          <el-tag v-else-if="scope.row.job==5">咨询师</el-tag>
          <el-tag v-else>其他</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="entryDate" label="入职日期" width="120" align="center"/>
      <el-table-column prop="updateTime" label="最后操作时间" width="200" align="center"></el-table-column>
      <el-table-column label="操作" align="center" >
        <template #default="scope">
          <el-button type="primary"  @click="edit(scope.row.id)"><el-icon><EditPen /></el-icon>修改</el-button>
          <el-button type="danger" @click="deleteId(scope.row.id)"><el-icon><Delete /></el-icon>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
</div>
<!-- 分页 -->
<div>
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
</div>

<!-- 弹框表格数据 -->
<div>
  <el-dialog v-model="dialogShow" :title="table">
    <el-form :model="empExprList" :rules="rules" ref="ruleFormRef">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
            <el-input v-model="empExprList.username" placeholder="请输入用户名"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
            <el-input v-model="empExprList.name" placeholder="请输入员工姓名"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12"> 
          <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
            <el-select v-model="empExprList.gender" placeholder="请选择">
              <el-option label="男" value="1" />
              <el-option label="女" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12"> 
          <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
            <el-input v-model="empExprList.phone" placeholder="请输入员工手机号"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12"> 
          <el-form-item label="职位" :label-width="formLabelWidth">
            <el-select v-model="empExprList.job" placeholder="请选择">
              <el-option v-for="item in jobName" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12"> 
          <el-form-item label="薪资" :label-width="formLabelWidth">
            <el-input v-model="empExprList.salary" placeholder="请输入员工薪资"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12"> 
          <el-form-item label="所属部门" :label-width="formLabelWidth">
            <el-select v-model="empExprList.deptId" placeholder="请选择">
              <el-option v-for="item in deptList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12"> 
          <el-form-item label="入职时间" :label-width="formLabelWidth">
            <el-date-picker v-model="empExprList.entryDate" type="date" placeholder="请选择入职日期" value-format="YYYY-MM-DD" style="width: 100%;"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 头像上传 -->
    <el-form-item label="头像">
      <el-upload class="avatar-uploader"
        action="/api/upload"
        :headers="token"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <img v-if="empExprList.image" :src="empExprList.image" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>
    <el-form-item label=" + 添加工作经历">
        <el-button type="success" @click="addExprWork" >添加工作经历</el-button>
    </el-form-item>
  
    <el-row :gutter="3" v-for="(item,index) in empExprList.exprList">
      <el-col :span="10">
        <el-form-item label="时间">
          <el-date-picker v-model="item.exprDate" type="daterange" range-separator="到"
            start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" :size="default"/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="公司" :label-width="formLabelWidth">
          <el-input v-model="item.company" placeholder="请输入公司名称"/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="职位" :label-width="formLabelWidth">
          <el-input v-model="item.job" placeholder="请输入职位"/>
        </el-form-item>
      </el-col>
      <el-col :span="2"><el-button type="danger" @click="deleteExpr(index)">删除</el-button></el-col>
    </el-row>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogShow = false">取消</el-button>
        <el-button type="primary" @click="save" >保存</el-button>
      </div>
    </template>
  </el-dialog>
</div>
</template>


<style scoped>
/* 弹窗中按钮的显示位置在中央 */
.dialog-footer {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;      /* 垂直居中（可选） */
  gap: 10px;                /* 按钮之间留出间距（可选） */
}
/* 头像上传样式 */
.avatar-uploader {
  border: 1px dashed #ccc;
  border-radius: 8px;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 8px;
}
.avatar-uploader-icon {
  font-size: 24px;
  color: #8c939d;
}
</style>